from Common.HITPropertiesTemplate import HITPropertiesTemplate
#from Common.QuestionFormTemplate import QuestionFormTemplate
#from Common.Reward import Reward
from Common.Campaign import Campaign
from Common.Client import Client
from Controller.BaseController import BaseController
from Utility import TemplateValueName, UserRole, FormData, ViewName, SessionKey
from google.appengine.ext import db
from Biz.CsvHandler import HITCsvHandler
import string

class CreateHITController(BaseController):
    def get(self):
        """
        Verify user role
            redirect user to login page
        or
            return "Create HIT" page to user
        """
        
        # user has not logged in
        u = self.GetCurrentUser()
        
        # check user role, otherwise redirect user to "Access Deny"
        # ToDo: Privilege Issue
        if not self.VerifyCurrentUserRole(u, UserRole.User, "/create/hit"):
            return
        
        # user has log in
        if u.Ref_Group is not None:
            g = u.Ref_Group
        else:
            # ToDo:Log error message
            return self.redirect("/errors")

        template_values = {TemplateValueName.CLIENTS:g.Clients, 'HITPropertiesTemplates': u.Ref_Company.HITPropertiesTemplates, 'HITQuestionTemplates':u.Ref_Company.QuestionFormTemplates}
        self.Render(ViewName.CREATE_HIT, template_values)



    def post(self):
        """
        Verfiy user role
            redirect user to login page
        or
            gather user inputs, generate questionform, save HITs to session, redirect USER to preview page
        """
        u = self.GetCurrentUser()
        if not self.VerifyCurrentUserRole(u, UserRole.User, "/create/hit"):
            return
        
        # user has log in
        if u.Ref_Group is not None:
            g = u.Ref_Group
        else:
            # ToDo:Log error message
            return self.redirect("/errors")
        
        template_values = {}
        
        """
            Step 1 form data
        """
        cid = self.request.get(FormData.CLIENT_KEY)
        campaignkey = self.request.get(FormData.CAMPAIGN_KEY)
        
        if cid == "0" or campaignkey == "0":
            template_values = {TemplateValueName.CLIENTS:g.Clients, 'HITPropertiesTemplates': u.Ref_Company.HITPropertiesTemplates, 'HITQuestionTemplates':u.Ref_Company.QuestionFormTemplates, "message":"There are something wrong with step 1"}
            self.Render(ViewName.CREATE_HIT, template_values)
            return

        """
            Step 2 Form data
        """
        templateName = self.request.get(FormData.HIT_TEMPLATE_NAME)
        title = self.request.get(FormData.HIT_TEMPLATE_TITLE)
        description = self.request.get(FormData.HIT_TEMPLATE_DESCRIPTION)
        keywords = self.request.get(FormData.HIT_TEMPLATE_KEYWORDS)

        assignmentDuration = string.atoi(self.request.get(FormData.HIT_TEMPLATE_ASSIGNMENT_DURATION))
        assignmentDurationUnit = self.request.get(FormData.HIT_TEMPLATE_ASSIGNMENT_DURATION_UNIT)

        lifetime = string.atoi(self.request.get(FormData.HIT_TEMPLATE_LIFETIME))
        lifetimeUnit = self.request.get(FormData.HIT_TEMPLATE_LIFETIME_UNIT)

        #reward = 0.01 #string.atof(self.request.get(FormData.HIT_TEMPLATE_REWARD))
        maxAssignments = string.atoi(self.request.get(FormData.HIT_TEMPLATE_MXA_ASSIGNMENTS))

        autoApprovalDelay = string.atoi(self.request.get(FormData.HIT_TEMPLATE_AUTO_APPROVAL_DELAY))
        autoApprovalDelayUnit = self.request.get(FormData.HIT_TEMPLATE_AUTO_APPROVAL_DELAY_UNIT)

        try:
            hitPropertiesTempate = HITPropertiesTemplate(
                parent=u.Ref_Group,
                key_name=templateName,
                TemplateName=templateName,
                Title=title,
                Description=description,
                Keywords=keywords,
                AssignmentDuration=assignmentDuration,
                AssignmentDurationUnit=assignmentDurationUnit,
                Lifetime=lifetime,
                LifetimeUnit=lifetimeUnit,
                MaxAssignments=maxAssignments,
                AutoApprovalDelay=autoApprovalDelay,
                AutoApprovalDelayUnit=autoApprovalDelayUnit
            )
            #rw = Reward(
            #    parent=hitPropertiesTempate,
            #    FormattedPrice=reward,
            #    Amount=long(reward * 100)
            #)
        except db.BadValueError:
            template_values = {TemplateValueName.CLIENTS:g.Clients, 'HITPropertiesTemplates': u.Ref_Company.HITPropertiesTemplates, 'HITQuestionTemplates':u.Ref_Company.QuestionFormTemplates, "message":"There are something wrong with step 2"}
            self.Render(ViewName.CREATE_HIT, template_values)
            return
            
        """
            Step 3 Form data
        """
        #questionName = self.request.get(FormData.HIT_TEMPLATE_QUESTION_NAME)
        #frameHeight = string.atoi(self.request.get(FormData.HIT_TEMPLATE_QUESTION_FRAMEHEIGHT))
        metaHtml = self.request.get(FormData.HIT_TEMPLATE_QUESTION_METAHTML)
        
                        
        handleResult = HITCsvHandler(self.request.get(FormData.UPLOAD_FILE), metaHtml)
        if not handleResult["isok"]:
            template_values = {TemplateValueName.CLIENTS:g.Clients, 'HITPropertiesTemplates': u.Ref_Company.HITPropertiesTemplates, 'HITQuestionTemplates':u.Ref_Company.QuestionFormTemplates, "message":handleResult["message"]}
            self.Render(ViewName.CREATE_HIT, template_values)
            return
        for hit in handleResult["hitdata"]:
            hit.Title = hitPropertiesTempate.Title
            hit.Description = hitPropertiesTempate.Description
            hit.Keywords = hitPropertiesTempate.Keywords
            
            lifeUnit = 60
            if hitPropertiesTempate.LifetimeUnit == "Days":
                lifeUnit = 86400
            elif hitPropertiesTempate.LifetimeUnit == "Hours":
                lifeUnit = 3600                
            hit.LifetimeInSeconds = hitPropertiesTempate.Lifetime * lifeUnit
            
#            maxUnit = 60
#            if hitPropertiesTempate.AssignmentDurationUnit == "Days":
#                maxUnit = 86400
#            elif hitPropertiesTempate.AssignmentDurationUnit == "Hours":
#                maxUnit = 3600
#            hit.MaxAssignments = hitPropertiesTempate.MaxAssignments * maxUnit
#            hit.RequesterAnnotation = db.StringProperty() 
            assignmentUnit = 60
            if hitPropertiesTempate.AssignmentDurationUnit == "Days":
                assignmentUnit = 86400
            elif hitPropertiesTempate.AssignmentDurationUnit == "Hours":
                assignmentUnit = 3600
            hit.AssignmentDurationInSeconds = hitPropertiesTempate.AssignmentDuration * assignmentUnit
            
            hit.MaxAssignments = maxAssignments
            
            """
            If there are no auto approval dealy in the csv file, or the value is invalid, we will
            use the default value which get from step 2 UI.
            """
            if hit.AutoApprovalDelayInSeconds == -1:
                autoUnit = 60
                if hitPropertiesTempate.AutoApprovalDelayUnit == "Days":
                    autoUnit = 86400
                elif hitPropertiesTempate.AutoApprovalDelayUnit == "Hours":
                    autoUnit = 3600
                hit.AutoApprovalDelayInSeconds = hitPropertiesTempate.AutoApprovalDelay * autoUnit
            
            hit.Ref_Requester = u
            hit.Ref_Campaign = Campaign.get(campaignkey)
            hit.Ref_Client = Client.get(cid)
            hit.Ref_Company = u.Ref_Company
        
        self.SetSessionItem(SessionKey.CURRENT_HIT_DATA, handleResult["hitdata"])
        self.SetSessionItem(SessionKey.CURRENT_HIT_CSV_DATA, handleResult["csvdata"])
        return self.redirect("/preview/hit")

        self.Render(ViewName.CREATE_HIT_TEMPLATE, template_values)
